const router = require('koa-router')()
const sequelize = require('../../dbHelper/db')
const { sys_user, sys_user_post, sys_user_role, sys_dept, sys_role, sys_menu } = require('../../dbHelper/db').models
const { Op } = require('sequelize')
const { toTreeByRecursion } = require('../../utils')

router.prefix('/user')

const tokens = {
  admin: {
    token: 'admin-token'
  },
  editor: {
    token: 'editor-token'
  }
}

const users = {
  'admin-token': {
    roles: ['admin'],
    introduction: 'I am a super administrator',
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    name: 'Super Admin'
  },
  'editor-token': {
    roles: ['editor'],
    introduction: 'I am an editor',
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    name: 'Normal Editor'
  }
}

router.get('/info', async(ctx) => {
  console.log(ctx.request.query)
  const { token } = ctx.request.query

  const info = users[token]

  // mock error
  if (!info) {
    ctx.body = {
      code: 50008,
      message: 'Login failed, unable to get user details.'
    }
  } else {
    ctx.body = {
      code: 20000,
      data: info
    }
  }
})

router.get('/addPost', (ctx) => {
  console.log(ctx.query.name)
  ctx.body = {

    title: 'addPost'
  }
})

router.post('/login', async(ctx) => {
  const { username } = ctx.request.body
  const token = tokens[username]

  // mock error
  if (!token) {
    return {
      code: 60204,
      message: 'Account and password are incorrect.'
    }
  }

  ctx.body = {
    code: 20000,
    data: token
  }
})

router.post('/addUser', async(ctx) => {
  const params = ctx.request.body

  let objUser = await sys_user.findOne({
    where: {
      [Op.or]: [
        { user_name: params.user_name }
      ]
    }
  })

  if (objUser) {
    ctx.body = {
      code: -1,
      msg: '岗位名称或岗位ID重复，创建失败！'
    }
  } else {
    const t = await sequelize.transaction()

    try {
      objUser = await sys_user.create({
        dept_id: params.dept_id,
        user_name: params.user_name,
        nick_name: params.nick_name,
        email: params.email,
        phonenumber: params.phonenumber,
        sex: params.sex,
        avatar: params.avatar,
        password: params.password,
        status: params.status,
        remark: params.remark
      }, { transaction: t })

      const { role_ids, post_ids } = ctx.request.body

      if (Array.isArray(role_ids)) {
        const insertSql = role_ids.map((role_id) => {
          return {
            user_id: objUser.user_id,
            role_id: role_id
          }
        })

        await sys_user_role.bulkCreate(insertSql, { transaction: t })
      }

      if (Array.isArray(post_ids)) {
        const insertSql = post_ids.map((post_id) => {
          return {
            user_id: objUser.user_id,
            post_id: post_id
          }
        })

        await sys_user_post.bulkCreate(insertSql, { transaction: t })
      }

      t.commit()

      ctx.body = {
        code: 0,
        msg: '创建成功！',
        data: objUser
      }
    } catch (error) {
      t.rollback()
    }
  }
})

router.get('/getUserList', async(ctx) => {
  // 请求参数校验
  ctx.verifyParams({
    page_num: { type: 'string', required: true },
    page_size: { type: 'string', required: true }
  })

  const query = ctx.request.query

  const where = {}

  const resultJson = await sys_user.findAndCountAll({
    where,
    include: {
      model: sys_dept,
      as: 'dept'
    },
    offset: (query.page_num - 1) * query.page_size,
    limit: +query.page_size
  })

  ctx.body = {
    code: 0,
    data: resultJson,
    msg: 'ok'
  }
})

router.get('/getUserRoutes', async(ctx) => {
  const query = ctx.request.query

  let objUser = await sys_user.findByPk(query.user_id, {
    include: [
      {
        model: sys_role,
        attributes: ['role_id'],
        include: [
          {
            model: sys_menu
          }
        ]
      }
    ]
  })

  const result = []

  if (objUser) {
    objUser = objUser.toJSON()
    objUser.sys_roles.forEach((role) => {
      role.sys_menus.forEach((menu) => {
        if (!result.find((item) => item.menu_id === menu.menu_id)) {
          result.push(menu)
        }
      })
    })
  }

  const treeData = toTreeByRecursion(result, 'menu_id', 'parent_id', 0, 'children')

  ctx.body = {
    code: 0,
    data: treeData,
    msg: 'ok'
  }
})

module.exports = router
